<?php include_once "top.php";
$user=$db->ig2_want('mae_user','id='.$_GET['id'].' and is_delete=0');
if(!$user) tellgoto('','user.php');

// 取得分组商品列表
$now = time();
$activeProductSql = " SELECT distinct p.id FROM mae_prize p";
$activeProductSql .= " INNER JOIN mae_rel_user_exchange_activity_product rueap ON rueap.productid = p.id";
$activeProductSql .= " INNER JOIN mae_user_exchange_activity uea ON uea.id = rueap.activityid";
$activeProductSql .= " INNER JOIN mae_rel_user_exchange_activity_group rueag ON rueag.activityid = uea.id";
$activeProductSql .= " INNER JOIN mae_group g ON g.id = rueag.groupid";
$activeProductSql .= " INNER JOIN mae_rel_group_shop rgs ON rgs.groupid = g.id";
$activeProductSql .= " INNER JOIN mae_shop s ON s.id = rgs.shopid";
$activeProductSql .= " INNER JOIN mae_role r ON r.shop_id = s.id";
$activeProductSql .= " INNER JOIN mae_user u ON u.id = r.uid";
$activeProductSql .= " WHERE u.id = ".$user['id']." AND uea.starttime <= ".$now." AND uea.endtime >= ".$now." AND uea.status = 1";
$activeProductList = $db->ig2_query_select($activeProductSql);

$where = "1<>1";
if ($activeProductList) {
    $where = " temp.id IN (";
    foreach($activeProductList as $product) {
        $where .= $product['id'].",";
    }
    $where = substr($where, 0, strlen($where) - 1);
    $where .= ")";
}

// 商品列表
$productList = $db->ig2_query_select('SELECT temp.id, temp.name, temp.need_integral, temp.img, temp.is_virtual FROM '.
    '(SELECT * FROM mae_prize WHERE status = 0 AND is_virtual = 0 AND stock > 0'.
    ' UNION '.
    ' SELECT p.* FROM mae_prize p WHERE p.status = 0 AND p.is_virtual = 1 AND exists(SELECT 1 FROM mae_prize_virtual v WHERE v.prize_id = p.id AND v.is_used = 0)) temp'.
    ' WHERE '.$where.
    ' ORDER BY temp.istop DESC, temp.create_time DESC');

// 本月已使用积分
$stime=date('Y-m-01', strtotime(date("Y-m-d")));//当月开始时间 Y-m-d格式
$etime=strtotime("$stime +1 month");//当月结束时间 时间戳
$stime=strtotime($stime);//当月开始时间 时间戳

$usedScore = $db->ig2_query_select("SELECT sum(l.num * p.need_integral) as usedScore FROM mae_shop_user_exchange_list l INNER JOIN mae_prize p ON l.prize_id = p.id WHERE l.uid = ".$user['id']." AND l.create_time >=".$stime." AND l.create_time < ".$etime);
if ($usedScore && $usedScore[0]['usedScore']) {
    $usedScore = $usedScore[0]['usedScore'];
} else {
    $usedScore = 0;
}

?>

<input type="hidden" id="userid" value="<?php echo($user['id'])?>" />
<div class="container">
	<div class="p7">
		<img class="p7bg bg" src="images/p7bg.jpg">
		<div id="p7bar">
			<?php
            foreach($productList as $product) {
            ?>
                <li data-id="<?php echo $product['id']?>" data-integral="<?php echo $product['need_integral']?>" data-name="<?php echo $product['name']?>" data-virtual="<?php echo $product['is_virtual']?>">
                    <img class="p7libg"  src="images/p7libg.jpg">
                    <img class="txt p7_1"  src="<?php echo $product['img']?>">
                    <img class="txt p7_2" id="p7li<?php echo $product['id']?>_3" src="images/p7_2.png">
                    <img class="txt jia" id="p7li<?php echo $product['id']?>_1" src="images/jia.png">
                    <img class="txt jian" id="p7li<?php echo $product['id']?>_2" src="images/jian.png">
                    <span class="p2text p7text_1" ><?php echo $product['name']?></span>
                    <span class="txt p7text_2" ><font id="p7font_<?php echo $list['id']?>"><?php echo $product['need_integral']?></font>积分</span>
                    <input class="p7text_3 txt" id="p7input_<?php echo $product['id']?>" type="text" readonly="readonly" value="0">
                    <input class="prize" id="prize_<?php echo $product['id']?>" type="hidden" name="prize" value="0">
                </li>
            <?php
            }
            ?>
		</div>  
		
		<img class="txt tishi"  src="images/tishi.png"> 
		 
   		<div id="footer">
			<img id="p7ftbg" src="images/p7ftbg.jpg">
	   	 	<span class="p2text" id="fttext">
                提示：当周球票最晚请于周三兑换。<br/>
				当前可用积分<font color="#f00"><?php echo $user['score']-$user['used_score']?></font>分，
				本次兑换积分<font id="p7font" color="#f00">0</font>分
			</span>
			<img class="txt" id="p7bt" src="images/p7bt.jpg">	
		</div>
		<div id="qingdan">
			<img id="qdbg" src="images/qdbg.jpg">
			<div id="qdbar"></div>	
			<img class="txt" id="qd_1" src="images/qd_1.jpg">
			<img class="txt" id="qd_2" src="images/qd_2.jpg">
		</div>
		<img id="qdmb" src="images/qdmb.png" style="z-index:12">
		<img id="qdmb_2" src="images/p2bar_3.png" style="z-index:12">
		<div id="wuliu">
			<img id="wlbg" src="images/wlbg.jpg">	
			<img class="txt" id="wl_1" src="images/wl_1.png">
			<img class="txt" id="wl_2" src="images/wl_2.png">
			<input class="ipt" id="nm" type="text" name="" value="<?php echo $user['name']?>">
			<input class="ipt" id="tel" type="text" name="" value="<?php echo $user['phone']?>">
			<input class="ipt" id="add" type="text" name="" value="<?php echo $user['address']?>">
		</div>
		<div id="tijiao">
			<img id="tjbg" src="images/tjbg.png">	
			<img class="txt" id="tj_1" src="images/tj_1.png" onclick="location.href='shop.php?id=<?php echo $user['id']?>'">
			<img class="txt" id="tj_2" src="images/tj_2.png" onclick="location.href='clerk.php?id=<?php echo $user['id']?>&source=user'">
			<img class="txt" id="tj_3" src="images/p2bar_3.png" onclick="location.href='shop.php?id=<?php echo $user['id']?>'">
		</div>
	</div>
</div>
<script type="text/javascript">
    // 本月已使用的积分
    var monthUsedScore = <?php echo $usedScore?>;
    // 本次选择的积分
    var currentUsedScore = 0;
    // 现在可使用的积分
    var ihave=<?php echo $user['score']-$user['used_score']?>;//用户现有积分
$(document).ready(function() {
	$('.tishi').click(function(){
		$('.tishi').fadeOut(500);	
	});
	
	$('#qd_2').click(function(){
		$('#qingdan').fadeOut(500);
		document.getElementById('qd_2').src='images/qd_2_h.jpg';
		setTimeout("document.getElementById('qd_2').src='images/qd_2.jpg'",1000);
	});
	
	$('#tj_3').click(function(){
		$('#tijiao').fadeOut(500);
	});
	
	$('#qdmb_2').click(function(){
		$('#qdmb,#qdmb_2,#qingdan').fadeOut(500);
	});
	
	$('#wl_2').click(function(){
		$('#wl_1').unbind('click');
		$('#wuliu').fadeOut(500);
	});
	
	$('.p7_2').click(function(){
        var id = $(this).parent("li").data("id");
        var needIntegral = $(this).parent("li").data("integral");
        var currentNum = $(this).parent("li").find(".p7text_3").val();

        if (currentNum == 0) {
            currentNum++;
            currentUsedScore += needIntegral;

            if (currentUsedScore + monthUsedScore > 600) {
                currentUsedScore -= needIntegral;
                $('#qdmb,#qdmb_2').fadeIn(500);
            } else if (currentUsedScore > ihave){
                currentUsedScore -= needIntegral;
                $('.tishi').fadeIn(500);
            } else {
                $(this).parent("li").find(".p7_2").attr('src','images/p7_3.png');
                $(this).parent("li").find(".p7text_3").val(currentNum);
                $('#p7font').text(currentUsedScore);
            }
        } else {
            currentUsedScore -= needIntegral * currentNum;

            $(this).parent("li").find(".p7text_3").val(0);
            $('#p7font').text(currentUsedScore);
            $(this).parent("li").find(".p7_2").attr('src','images/p7_2.png');
        }
	});
	
});	

//生成兑换清单
$('#p7bt').click(function(){
    var selectedObj = {};
    selectedObj.totalScore = 0;
    selectedObj.items = [];
    $("#p7bar").find("li").each(function(){
        var productName = $(this).data("name");
        var needIntegral = parseInt($(this).data("integral"));

        var num = parseInt($(this).find(".p7text_3").val());

        if (num > 0) {
            var selectedItem = {};
            selectedItem.name = productName;
            selectedItem.score = needIntegral * num;
            selectedItem.num = num;
            selectedObj.items.push(selectedItem);
            selectedObj.totalScore += needIntegral * num;
        }
    });

    if (selectedObj.items.length == 0) {
        alert('请您选择需要兑换的商品');
    } else {
        var html = "";
        for(var i = 0; i < selectedObj.items.length; i++) {
            var item = selectedObj.items[i];
            var li = '<li>';
            li += '<span class="qdtext_1 qdtext">' + item.name + '</span>'
            li += '<span class="qdtext_2 qdtext">' + item.num + '</span>'
            li += '<span class="qdtext_3 qdtext">' + item.score + '</span>'
            li += '</li>'

            html += li;
        }

        html += '<div id="qdbox">';
        html += '<img id="qd_3" src="images/qd_3.png">';
        html += '<span class="qdbox_1 txt">' + selectedObj.totalScore + '</span>';
        html += '</div>'

        $('#qdbar').html(html);
        getWidth();
        $('#qingdan').fadeIn(500);
    }
});

//兑换商品
$('#qd_1').click(function(){
    var uid = $("#userid").val();
    // 是否需要物流
    var needWuliu = false;
    // 选择的商品列表
    var selectedArray = [];
    var totalScore = 0;
    $("#p7bar").find("li").each(function(){
        var productId = $(this).data("id");
        var num = parseInt($(this).find(".p7text_3").val());
        var score = parseInt($(this).data("integral"));
        var isVirtual = $(this).data("virtual");

        if (num > 0) {
            var selectedItem = {};
            selectedItem.id = productId;
            selectedItem.num = num;
            selectedArray.push(selectedItem);
            totalScore += num * score;

            if (isVirtual == '0') {
                needWuliu = true;
            }
        }
    });

    if (needWuliu) {
        $('#wuliu').fadeIn(500);
        $('#wl_1').unbind("click").bind("click",function(){
			if(checkWuliu()){
				var name=$('#nm').val();
				var phone=$('#tel').val();
				var address=$('#add').val();

                $.ajax({
                    type: "GET",
                    url: "ra_ajax_repairman_market.php?method=exchangeRepairmanScore&userid="+uid+"&selectedarray="+JSON.stringify(selectedArray)+"&totalscore="+totalScore+"&name="+name+"&phone="+phone+"&address="+address,
                    dataType: 'json',
                    success: function(data){
                        if(data.errcode == 0){
                            $('#tijiao').fadeIn(500);
                        }else{
                            if(data.errcode == 1){
                                $('#qdmb,#qdmb_2').fadeIn(500);
                            }else if(data.errcode == 2){
                                $('.tishi').fadeIn(500);
                            }else if(data.errcode == 3 || data.errcode == 4){
                                alert(data.errmsg);
                            }else{
                                window.location.reload();
                            }
                        }
                    }
                });
			}
		});
    } else {
        $.ajax({
			type: "GET",
			url: "ra_ajax_repairman_market.php?method=exchangeRepairmanScore&userid="+uid+"&selectedarray="+JSON.stringify(selectedArray)+"&totalscore="+totalScore,
            dataType: 'json',
			success: function(data){
				if(data.errcode == 0){
					$('#tijiao').fadeIn(500);
				}else{
					if(data.errcode == 1){
						$('#qdmb,#qdmb_2').fadeIn(500);
					}else if(data.errcode == 2){
						$('.tishi').fadeIn(500);
					}else if(data.errcode == 3 || data.errcode == 4){
                        alert(data.errmsg);
                    }else{
						window.location.reload();
					}
				}
			}
		});
    }
});

$('.jia').click(function(){
    var id = $(this).parent("li").data("id");
    var needIntegral = $(this).parent("li").data("integral");
    var currentNum = $(this).parent("li").find(".p7text_3").val();

    currentNum++;
    currentUsedScore += needIntegral;

    if (currentUsedScore + monthUsedScore > 600) {
        currentUsedScore -= needIntegral;
        $('#qdmb,#qdmb_2').fadeIn(500);
    } else if (currentUsedScore > ihave){
        currentUsedScore -= needIntegral;
        $('.tishi').fadeIn(500);
    } else {
        $(this).parent("li").find(".p7_2").attr('src','images/p7_3.png');
        $(this).parent("li").find(".p7text_3").val(currentNum);
        $('#p7font').text(currentUsedScore);
    }
});

$('.jian').click(function(){
    var id = $(this).parent("li").data("id");
    var needIntegral = $(this).parent("li").data("integral");
    var currentNum = $(this).parent("li").find(".p7text_3").val();

    if (currentNum > 0) {
        currentNum--;
        currentUsedScore -= needIntegral;

        $(this).parent("li").find(".p7text_3").val(currentNum);
        $('#p7font').text(currentUsedScore);

        if (currentNum <= 0) {
            $(this).parent("li").find(".p7_2").attr('src','images/p7_2.png');
        }
    }
});

function monthlylimit(need){
	var uid='<?php echo $user['id']?>';
	$.ajax({
		type: "GET",
		url: "ra_ajax.php?monthly_limit=1&uid="+uid+"&need_integral="+need,
		success: function(data){
			if(data == 'yes'){
				$('#qdmb,#qdmb_2').fadeIn(500);
				mark=false;
			}else{
				mark=true;
			}
		}
	});
}

//删除左右两端的空白字符
function trim(str){
	return str.replace(/(^\s*)|(\s*$)/g, "");
}

function checkWuliu() {
    if (trim(document.getElementById('nm').value) == '') {
        alert('请输入姓名~');
        return false;
    }

    var phone = document.getElementById('tel').value;
    var myregPhone = /^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/i;
    if (trim(phone) == '') {
        alert('请输入电话~');
        return false;
    } else {
        if (!myregPhone.test(phone)) {
            alert('请输入正确的电话号码');
            return false;
        }
    }
    if (trim(document.getElementById('add').value) == '') {
        alert('请输入地址~');
        return false;
    }
    return true;
}

function getWidth(){
	$('.p1,.p2,.p3,.p4,.container,.bg').width(x);
	$('.p1,.p2,.p3,.p4,.p5,.p6,.p7,.p8').css({left:0,top:0});
	//p3
	$('#p7bar').width(638/p).height(730/p).css({left:(x-638/p)/2+'px',top:157/p+'px',paddingBottom:30/p+'px'});
	$('#p7bar li').width(638/p).height(238/p).css({marginTop:10/p+'px'});
	$('.p7libg').width(638/p).height(238/p);
	$('.p7_1').width(185/p).height(130/p).css({left:125/p+'px',top:55/p+'px'});
	$('.p7_2').width(47/p).height(47/p).css({left:28/p+'px',top:99/p+'px'});
	$('.jia').width(65/p).height(68/p).css({left:525/p+'px',top:136/p+'px'});
	$('.jian').width(65/p).height(68/p).css({left:352/p+'px',top:136/p+'px'});
	$('.p7text_1').css({left:351/p+'px',top:34/p+'px',fontSize:26/p+'px',paddingRight:20/p+'px'});
	$('.p7text_2').css({left:351/p+'px',top:95/p+'px',fontSize:26/p+'px'});
	$('.p7text_3').css({width:107/p+'px',height:68/p+'px',left:419/p+'px',top:136/p+'px',fontSize:30/p+'px'});
	$('.tishi').width(x).css({left:0,top:0});
	$('#footer,#p7ftbg').width(x).height(280/p);
	$('#footer').css({left:0,bottom:0});
	$('#p7bt').width(632/p).height(141/p);
	$('#p7bt').css({left:(x-632/p)/2+'px',top:147/p+'px'});
	$('#fttext').css({left:0,top:55/p+'px',width:x,fontSize:32/p+'px'});
	$('#qingdan').width(x).css({left:0,top:0});	
	$('#qdbg').width(x);
	$('#qdbar').width(562/p).height(576/p).css({left:(x-562/p)/2+'px',top:306/p+'px'});
	$('#qdbar li').css({width:562/p+'px',height:50/p+'px',marginTop:30/p+'px'});
	$('.qdtext_1').css({left:0,top:0,width:340/p+'px',fontSize:24/p+'px'});
	$('.qdtext_2').css({left:386/p+'px',top:0,width:100/p+'px',fontSize:24/p+'px'});
	$('.qdtext_3').css({left:500/p+'px',top:0,width:60/p+'px',fontSize:24/p+'px'});
	$('#qdbox').width(562/p).height(80/p);
	$('#qdbox').css({marginTop:30/p+'px'});
	$('#qd_3').width(556/p).height(57/p).css({left:0,top:0});
	$('.qdbox_1').css({right:20/p+'px',bottom:20/p+'px',fontSize:24/p+'px'});
	$('#qd_1').width(254/p).height(76/p).css({left:75/p+'px',top:1010/p+'px'});
	$('#qd_2').width(254/p).height(76/p).css({left:390/p+'px',top:1010/p+'px'});
	$('#wuliu').width(x).css({left:0,top:0});
	$('#wlbg').width(x);
	$('#wl_1').width(134/p).height(76/p).css({left:(x-134/p)/4+'px',top:1010/p+'px'});
	$('#wl_2').width(134/p).height(76/p).css({right:(x-134/p)/4+'px',top:1010/p+'px'});
	$('#nm').css({left:248/p+'px',top:273/p+'px',width:406/p+'px',height:64/p+'px',fontSize:24/p+'px'});
	$('#tel').css({left:248/p+'px',top:387/p+'px',width:406/p+'px',height:64/p+'px',fontSize:24/p+'px'});
	$('#add').css({left:248/p+'px',top:502/p+'px',width:406/p+'px',height:64/p+'px',fontSize:24/p+'px'});
	$('#tijiao').width(x).css({left:0,top:0});
	$('#tjbg').width(x);
	$('#tj_1').width(134/p).height(76/p).css({left:(x-134/p)/2+'px',top:734/p+'px'});
	$('#tj_2').width(140/p).height(60/p).css({left:222/p+'px',top:498/p+'px'});
	$('#tj_3').width(30/p).height(32/p).css({left:641/p+'px',top:324/p+'px'});
	$('#qdmb').width(x).css({left:0,top:0});
	$('#qdmb_2').width(30/p).height(32/p).css({left:641/p+'px',top:450/p+'px'});
}
</script>
</body>
</html>